package top.btcmarket.auth.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;

import top.btcmarket.auth.config.RedisTokenManager;
import top.btcmarket.auth.entity.User;
import top.btcmarket.auth.service.UserService;
import top.btcmarket.auth.utils.EncryptUtil;
import top.btcmarket.common.constant.CommonConst;
import top.btcmarket.common.utils.JwtToken;

/**
 * 
 */
@RestController
public class AuthController {

	@Autowired
    private UserService userService;
	
	@Autowired
	private RedisTokenManager tokenManager ;
	
    @RequestMapping(value = "/auth/token",method = RequestMethod.POST)
    public ResponseEntity<?> createAuthenticationToken(@RequestBody User user1) {
    	System.out.println("------------AuthController---------------"+user1.getUsername()+"-----"+user1.getPassword());

    	//    	User user = userService.findByUsernameAndPassword(user1.getUsername(), user1.getPassword());
    	
    	User user = userService.findByUsername(user1.getUsername());
    	
        if (user != null) {
        	
        	String pwd = user.getPassword() ;
        	if(!EncryptUtil.match(user1.getPassword(), pwd)){
        		 System.out.println("无效的密码");
        		 return new ResponseEntity<String>("密码不正确", HttpStatus.FORBIDDEN);  
        	}
        	
//        	JwtToken jwt = new JwtToken();
//            final String randomKey = jwt.getRandomKey();
        	
        	
            final String token = JwtToken.generateToken(generalSubject(user));
            
            Map<String,String> reponse = new HashMap<String,String>();
            reponse.put("token", token);
            reponse.put("userName", user1.getUsername());
            
            tokenManager.cacheToken(token);
            
            return ResponseEntity.ok(reponse);
        } else {
            System.out.println("无效的用户");
            return new ResponseEntity<String>("该用户不存在", HttpStatus.FORBIDDEN);  
        }
    }
    
    @RequestMapping(value = "/auth/loginout",method = RequestMethod.GET)
    public ResponseEntity<?> loginOut(HttpServletRequest request) {
    	
    	System.out.println("------------loginOut---------------");
    	
    	Cookie[] cookies = request.getCookies();
		 if(cookies != null && cookies.length>0){
			 for (Cookie cookie : cookies) {
					System.out.println("---------auth--------"+cookie.getName()+"--------"+cookie.getValue());
				}
		 }
		 
    	//    	User user = userService.findByUsernameAndPassword(user1.getUsername(), user1.getPassword());
    	String token = request.getParameter(CommonConst.TOKEN_COOKIE_ID);
        if (StringUtils.isNotEmpty(token)) {
        	tokenManager.deleteToken(token);
            Map<String,String> reponse = new HashMap<String,String>();
            reponse.put("message", "用户注销成功!");
            
            return ResponseEntity.ok(reponse);
        } else {
            System.out.println("未找到token");
            return new ResponseEntity<String>("未找到token", HttpStatus.BAD_REQUEST);  
        }
    }
    
    /**
     * 生成subject信息
     * @param user
     * @return
     */
    public static String generalSubject(User user){
        
    	Map<String,String> userInfo = new HashMap<String,String>();
    	userInfo.put("username", user.getUsername());
    	userInfo.put(CommonConst.TOKEN_USER_ID, user.getId()+"");
    	userInfo.put("mobile", "1592564789");
    	userInfo.put(CommonConst.TOKEN_ORG_ID, "00000001");
    	userInfo.put(CommonConst.TOKEN_SCHEMA_NAME, "schema_ccsdb");
        return JSON.toJSONString(userInfo);
    }
}
